package com.hk.core.authentication.security.authentication.accesstoken;

import com.hk.commons.JsonResult;
import com.hk.commons.util.JsonUtils;
import com.hk.commons.util.StringUtils;
import com.hk.core.authentication.api.TokenGenerator;
import com.hk.core.web.Webs;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class AccessTokenAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final long ttl;

    private final TimeUnit unit;

    private final String cookieName;

    private final TokenGenerator tokenGenerator;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        Map<String, Object> claims = new HashMap<>();
        claims.put(AccessTokenConstant.SUBJECT, JsonUtils.serialize(principal));
        String token = tokenGenerator.generateToken(claims, ttl, unit);
        if (StringUtils.hasLength(cookieName)) {
            response.addCookie(newCookie(token));
        }
        Webs.writeJson(response, HttpServletResponse.SC_OK, JsonResult.success(Collections.singletonMap("token", token)));
    }

    private Cookie newCookie(String token) {
        Cookie cookie = new Cookie(cookieName, token);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge((int) unit.toSeconds(ttl));
        return cookie;
    }
}
